package com.uyayo.oms.cms.controller;

import com.uyayo.cms.dto.CmsArticleDTO;
import com.uyayo.cms.entity.*;
import com.uyayo.cms.model.CmsArticleCondition;
import com.uyayo.cms.service.CmsArticleCategoryRelService;
import com.uyayo.cms.service.CmsArticleService;
import com.uyayo.cms.service.CmsArticleTagRelService;
import com.uyayo.cms.service.CmsTagService;
import com.uyayo.framework.common.annotation.MethodName;
import com.uyayo.framework.message.enums.ResultMsgEnum;
import com.uyayo.framework.message.model.Result;
import com.uyayo.oms.cms.vo.CmsArticleVO;
import com.uyayo.oms.system.biz.ParamBiz;
import com.uyayo.framework.pagehelper.pojo.PageBean;
import com.uyayo.framework.pagehelper.pojo.PageResult;
import com.uyayo.system.authority.entity.SysUser;
import com.uyayo.ucenter.entity.Member;
import com.uyayo.ucenter.service.MemberService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.dozer.DozerBeanMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


/**
 * CmsArticleController
 * @author 乐乐科技.胡逢君
 * @date 2016-4-23下午4:03:35
 * @version 1.0
 */
@Controller
@RequestMapping("/cms/article")
public class CmsArticleController {

	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	private final ParamBiz paramBiz;

	private final CmsArticleService cmsArticleService;

	private  final MessageSource messageSource;

	private final DozerBeanMapper dozerBeanMapper;

	private final MemberService memberService;

	private final CmsArticleTagRelService cmsArticleTagRelService;

	private final CmsArticleCategoryRelService cmsArticleCategoryRelService;

	private final CmsTagService cmsTagService;


	@Autowired
	public CmsArticleController(CmsArticleService cmsArticleService, ParamBiz paramBiz, MessageSource messageSource, DozerBeanMapper dozerBeanMapper, MemberService memberService, CmsArticleTagRelService cmsArticleTagRelService, CmsArticleCategoryRelService cmsArticleCategoryRelService, CmsTagService cmsTagService) {
		this.cmsArticleService = cmsArticleService;
		this.paramBiz = paramBiz;
		this.messageSource = messageSource;
		this.dozerBeanMapper = dozerBeanMapper;
		this.memberService = memberService;
		this.cmsArticleTagRelService = cmsArticleTagRelService;
		this.cmsArticleCategoryRelService = cmsArticleCategoryRelService;
		this.cmsTagService = cmsTagService;
	}

	/**
	 * 页面跳转
	 */
	@RequestMapping(value={"index","/","home"},method=RequestMethod.GET)
	@RequiresPermissions("cms:article:index")
	public ModelAndView index(ModelAndView modelAndView) throws Exception {
		modelAndView.setViewName(paramBiz.getManagerTemplatesPrefix()+"cms/article/index");
		return modelAndView;
	}

	/**
	 * 获得模型列表
	 */
	@ResponseBody
	@RequestMapping("list")
	@RequiresPermissions("cms:article:search")
	@MethodName(value="内容管理->文章管理->查询列表",type=2)
	public List<CmsArticle> list(CmsArticleCondition cmsArticleCondition) {
		return cmsArticleService.selectArticle(cmsArticleCondition);
	}

	@ResponseBody
	@RequestMapping(value="search",method=RequestMethod.GET)
	@MethodName(value="内容管理->文章管理->搜索",type=2)
	@RequiresPermissions("cms:article:search")
	public PageResult<CmsArticle> selectCmsArticle(@RequestParam(value = "offset",required = false, defaultValue = "1") Integer start, //第几页
										  @RequestParam(value = "limit", required = false, defaultValue = "10") Integer pageSize,
											 String sort, String order, CmsArticleCondition cmsArticleCondition) {
		PageBean<CmsArticle> pageBean= new PageBean<>();
		try {
			pageBean = cmsArticleService.selectArticleByPaging((start / pageSize) + 1,pageSize,sort,order,cmsArticleCondition);
		} catch (Exception e) {
			e.printStackTrace();
		}
		PageResult<CmsArticle> pageResult = new PageResult<>();
		pageResult.setRows(pageBean.getList());
		pageResult.setTotal(pageBean.getTotalCount());
		return pageResult;
	}

	/**
	 * 进入新增表单
	 */
	@RequiresPermissions("cms:article:create")
	@RequestMapping(value = "add", method = RequestMethod.GET)
	public String add() {
		return paramBiz.getManagerTemplatesPrefix()+"cms/article/add";
	}

	/**
	 * 新建
	 */
	@ResponseBody
	@RequiresPermissions("cms:article:create")
	@RequestMapping(value = "add", method = RequestMethod.POST)
	@MethodName(value="内容管理->文章管理->新增",type=2)
	synchronized public Result add(HttpServletRequest request, CmsArticleVO cmsArticleVO, Errors errors) {
		try {
			if (errors.hasErrors()) {
				return Result.errorAndMsg(errors.getFieldError().getDefaultMessage());
			}
			Subject subject = SecurityUtils.getSubject();
			SysUser sysUser = (SysUser) subject.getPrincipal();
			Member member = memberService.getMemberByUsername(cmsArticleVO.getUsername());
			if(member==null){
				String message = messageSource.getMessage(ResultMsgEnum.USER_NOT_EXIST.getKey(),new Object[]{}, request.getLocale());
				logger.warn(message);
				return Result.error(ResultMsgEnum.USER_NOT_EXIST.code(),message);
			}
			CmsArticleDTO cmsArticleDTO = dozerBeanMapper.map(cmsArticleVO, CmsArticleDTO.class);
			cmsArticleDTO.setCreateTime(new Date());
			cmsArticleDTO.setMemberId(member.getId());
			cmsArticleDTO.setCreateBy(sysUser.getLoginname());
			int countSave = cmsArticleService.createCmsArticle(cmsArticleDTO);
			if(countSave<=0){
				String message = messageSource.getMessage("save.fail",new Object[]{}, request.getLocale());
				logger.info(message);
				return Result.build(400,message);
			}
		} catch (Exception e) {
			String message = messageSource.getMessage("server.error.500",new Object[]{}, request.getLocale());
			logger.error(message,e);
			return Result.build(500, message);
		}
		String message = messageSource.getMessage("save.success",new Object[]{}, request.getLocale());

		return Result.successAndMsg(message);
	}


	/**
	 * 进入查看页面
	 */
	@RequestMapping(value = "view", method = RequestMethod.GET)
	@MethodName(value="内容管理->文章管理->查看",type=2)
	@RequiresPermissions("cms:article:view")
	public ModelAndView view(ModelAndView modelAndView,HttpServletRequest request,Long id) {
		try {
			CmsArticle cmsArticle = cmsArticleService.getArticleById(id);
			Member member = memberService.getMemberById(cmsArticle.getMemberId());
			CmsArticleVO cmsArticleVO = dozerBeanMapper.map(cmsArticle,CmsArticleVO.class);
			if(member!=null){
				cmsArticleVO.setUsername(member.getUsername());
			}
			Example example = new Example(CmsArticleTagRel.class);
			Example.Criteria criteria = example.createCriteria();
			criteria.andEqualTo("articleId",id);
			List<CmsArticleTagRel>  cmsArticleTagRelList= cmsArticleTagRelService.selectByExample(example);
			List<Long> tags = cmsArticleTagRelList.stream()
					.map(CmsArticleTagRel::getTagId).collect(Collectors.toList());
			String articleTagIds = StringUtils.join(tags, ",");
			cmsArticleVO.setTagIds(articleTagIds);

			Example exampleC = new Example(CmsArticleCategoryRel.class);
			Example.Criteria criteriaC = exampleC.createCriteria();
			criteriaC.andEqualTo("articleId",id);
			List<CmsArticleCategoryRel> cmsArticleCategoryRelList = cmsArticleCategoryRelService.selectByExample(exampleC);
			List<Long> categorys = cmsArticleCategoryRelList.stream()
					.map(CmsArticleCategoryRel::getCategoryId).collect(Collectors.toList());
			String articleCategoryIds = StringUtils.join(categorys, ",");
			cmsArticleVO.setArticleCategoryIds(articleCategoryIds);
			modelAndView.addObject("cmsArticle",cmsArticleVO);
			modelAndView.setViewName(paramBiz.getManagerTemplatesPrefix()+"cms/article/view");
		} catch (Exception e) {
			String message = messageSource.getMessage("server.error.500",new Object[]{}, request.getLocale());
			logger.error(message,e);
		}
		return modelAndView;
	}

	@ResponseBody
	@RequestMapping(value = "update", method = RequestMethod.GET)
	@RequiresPermissions("cms:article:update")
	public ModelAndView update(ModelAndView modelAndView, HttpServletRequest request, Long id) {
		try {
			CmsArticle cmsArticle= cmsArticleService.getArticleById(id);
			Member member = memberService.getMemberById(cmsArticle.getMemberId());
			CmsArticleVO cmsArticleVO = dozerBeanMapper.map(cmsArticle,CmsArticleVO.class);
			if(member!=null){
				cmsArticleVO.setUsername(member.getUsername());
			}
			Example example = new Example(CmsArticleTagRel.class);
			Example.Criteria criteria = example.createCriteria();
			criteria.andEqualTo("articleId",id);
			List<CmsArticleTagRel>  cmsArticleTagRelList= cmsArticleTagRelService.selectByExample(example);
			List<Long> tags = cmsArticleTagRelList.stream()
					.map(CmsArticleTagRel::getTagId).collect(Collectors.toList());
			String articleTagIds = StringUtils.join(tags, ",");
			cmsArticleVO.setTagIds(articleTagIds);

			Example exampleC = new Example(CmsArticleCategoryRel.class);
			Example.Criteria criteriaC = exampleC.createCriteria();
			criteriaC.andEqualTo("articleId",id);
			List<CmsArticleCategoryRel> cmsArticleCategoryRelList = cmsArticleCategoryRelService.selectByExample(exampleC);
			List<Long> categorys = cmsArticleCategoryRelList.stream()
					.map(CmsArticleCategoryRel::getCategoryId).collect(Collectors.toList());
			String articleCategoryIds = StringUtils.join(categorys, ",");
			cmsArticleVO.setArticleCategoryIds(articleCategoryIds);
			modelAndView.addObject("cmsArticle",cmsArticleVO);
			modelAndView.setViewName(paramBiz.getManagerTemplatesPrefix()+"cms/article/update");
		} catch (Exception e) {
			String message = messageSource.getMessage("server.error.500",new Object[]{}, request.getLocale());
			logger.error(message,e);
		}
		return modelAndView;
	}

	/**
	 * 修改
	 */
	@ResponseBody
	@RequestMapping("update")
	@RequiresPermissions("cms:article:update")
	@MethodName(value="内容管理->文章管理->修改",type=2)
	synchronized public Result updateIcon(HttpServletRequest request, CmsArticleVO cmsArticleVO, Errors errors) {
		try {
			if (errors.hasErrors()) {
				return Result.errorAndMsg(errors.getFieldError().getDefaultMessage());
			}
			Subject subject = SecurityUtils.getSubject();
			SysUser sysUser = (SysUser) subject.getPrincipal();
			Member member = memberService.getMemberByUsername(cmsArticleVO.getUsername());
			if(member==null){
				String message = messageSource.getMessage(ResultMsgEnum.USER_NOT_EXIST.getKey(),new Object[]{}, request.getLocale());
				logger.warn(message);
				return Result.error(ResultMsgEnum.USER_NOT_EXIST.code(),message);
			}
			CmsArticleDTO cmsArticleDTO = dozerBeanMapper.map(cmsArticleVO,CmsArticleDTO.class);
			cmsArticleDTO.setMemberId(member.getId());
			cmsArticleDTO.setUpdateTime(new Date());
			cmsArticleDTO.setUpdateBy(sysUser.getLoginname());
			int count = cmsArticleService.updateArticle(cmsArticleDTO);
			if(count<=0){
				String message = messageSource.getMessage("save.fail",new Object[]{}, request.getLocale());
				logger.info(message);
				return Result.build(400,message);
			}
		} catch (Exception e) {
			String message = messageSource.getMessage("server.error.500",new Object[]{}, request.getLocale());
			logger.error(message,e);
			return Result.build(500, message);
		}
		String message = messageSource.getMessage("save.success",new Object[]{}, request.getLocale());

		return Result.successAndMsg(message);
	}

	/**
	 * 删除图标
	 */
	@ResponseBody
	@RequestMapping("delete")
	@RequiresPermissions("cms:article:delete")
	@MethodName(value="内容管理->文章管理->删除",type=2)
	public Result deleteArticle(HttpServletRequest request, Long id) {
		try {
			if (id==null) {
				String message = messageSource.getMessage("parameter.error",new Object[]{}, request.getLocale());
				logger.error(message);
				return Result.build(400,message);
			}
			int deleteCount = cmsArticleService.deleteArticle(id);
			if(deleteCount<=0){
				String message = messageSource.getMessage("delete.fail",new Object[]{}, request.getLocale());
				logger.error(message);
				return Result.build(400,message);
			}
		} catch(Exception e) {
			String message = messageSource.getMessage("server.error.500",new Object[]{}, request.getLocale());
			logger.error(message,e);
			return Result.build(500,message);
		}
		String message = messageSource.getMessage("delete.success",new Object[]{}, request.getLocale());
		logger.info(message);
		return Result.success(200,message);

	}
}
